﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Model
{
    public class FriendsService
    {
        public ServiceResult<PagedList<Data.Friend>> GetFriends(int userId, int start, int limit)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                UserRelationRepository reps = new UserRelationRepository(dbContext);

                PagedList<Data.Friend> pagedList = new PagedList<Data.Friend>();
                List<Data.Friend> list = reps.GetFriendList(userId, start, limit);

                pagedList.Start = start;
                pagedList.Limit = limit;
                pagedList.Total = reps.GetFriendCount(userId);
                pagedList.Items.AddRange(list);

                return new ServiceResult<PagedList<Data.Friend>>(ErrorCode.NoError, pagedList);
            }
        }

        /// <summary>
        /// 发送好友申请
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="targetUserId"></param>
        /// <returns></returns>
        public ServiceResult<string> SendRequest(int userId, int targetUserId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                if (userId == targetUserId)
                {
                    return new ServiceResult<string>(ErrorCode.SendFriendsRequest_SameUser);
                }

                UserRelationRepository reps = new UserRelationRepository(dbContext);

                // 检查是否存在好友关系
                UserRelation relation = reps.Get(targetUserId, userId, BasicData.UserRelationType.Friends);
                if (relation != null && relation.Status == BasicData.UserRelationStatus.Established)
                {
                    return new ServiceResult<string>(ErrorCode.SendFriendsRequest_HasRelation);
                }

                // 发送消息
                MessageRepository msgReps = new MessageRepository(dbContext);
                MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);
                AccountRepository aRep = new AccountRepository(dbContext);
                Account sender = aRep.Get(userId);
                if (sender == null)
                {
                    return new ServiceResult<string>(ErrorCode.SendFriendsRequest_SenderNotExist);
                }
                Account receiver = aRep.Get(targetUserId);
                if (receiver == null)
                {
                    return new ServiceResult<string>(ErrorCode.SendFriendsRequest_ReceiverNotExist);
                }

                // 为对方创建一个关系
                UserRelation friend2 = relation;
                if (friend2 == null)
                {
                    friend2 = new UserRelation();
                    friend2.Id = Guid.NewGuid();
                    friend2.UserId = targetUserId;
                    friend2.TargetUserId = userId;
                    friend2.Type = BasicData.UserRelationType.Friends;
                    friend2.Status = BasicData.UserRelationStatus.Building;
                    friend2.CreatedTime = DateTime.Now;
                    reps.Add(friend2);
                }

                string identityText = string.Format("FIREND_REQ{0}_{1}", targetUserId, userId);

                Message message = new Message();
                message.Id = Guid.NewGuid();
                message.ReceiverId = targetUserId;
                message.SenderId = userId;
                message.Type = BasicData.MessageType.SendFriendsRequest;
                message.Title = "好友申请";
                message.Content = string.Format("{0}希望添加您为好友", sender.NickName);
                message.CreatedTime = DateTime.Now;

                MessageClip messageSet = msgSetReps.Get(BasicData.MessageClipType.SystemNotice, identityText);
                if (messageSet == null)
                {
                    // 生成MessageSet
                    messageSet = new MessageClip();
                    messageSet.Id = Guid.NewGuid();
                    messageSet.IdentityText = identityText;
                    messageSet.Type = BasicData.MessageClipType.SystemNotice;
                    messageSet.MessageType = BasicData.MessageType.SendFriendsRequest;
                    messageSet.ReceiverId = targetUserId;
                    messageSet.MessageCount = 1;
                    messageSet.NewMessageCount = 1;
                    messageSet.CreatedTime = message.CreatedTime;
                    messageSet.LastestSenderId = message.SenderId;
                    messageSet.LastestContent = message.Content;
                    messageSet.LastestTitle = message.Title;
                    messageSet.LastestUpdatedTime = message.CreatedTime;

                    msgSetReps.Create(messageSet);
                }
                else
                {
                    messageSet.IsDeleted = false;
                    messageSet.MessageCount++;
                    messageSet.NewMessageCount = 1;
                    messageSet.CreatedTime = message.CreatedTime;
                    messageSet.LastestSenderId = message.SenderId;
                    messageSet.LastestContent = message.Content;
                    messageSet.LastestTitle = message.Title;
                    messageSet.LastestUpdatedTime = message.CreatedTime;

                    msgSetReps.Update(messageSet);
                }


                message.MessageClipId = messageSet.Id;
                msgReps.Create(message);
                


                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<string>(ErrorCode.NoError, null);
                }
                return new ServiceResult<string>(ErrorCode.DB_Error);
            }
        }

        public ServiceResult<UserRelation> AcceptRequest(int userId, int targetUserId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                UserRelationRepository reps = new UserRelationRepository(dbContext);
                UserRelation relation = reps.Get(userId, targetUserId, BasicData.UserRelationType.Friends);

                AccountRepository aReps = new AccountRepository(dbContext);
                Account user = aReps.Get(userId);

                if (relation != null)
                {
                    if (relation.Status == BasicData.UserRelationStatus.Established)
                    {
                        // 好友关系已存在
                        return new ServiceResult<UserRelation>(ErrorCode.NoError, relation);
                    }
                    else
                    {
                        relation.Status = BasicData.UserRelationStatus.Established;
                        relation.CreatedTime = DateTime.Now;
                        reps.Update(relation.Id, relation);
                        // 为对方创建一个关系
                        UserRelation friend = new UserRelation();
                        friend.Id = Guid.NewGuid();
                        friend.UserId = targetUserId;
                        friend.TargetUserId = userId;
                        friend.Type = BasicData.UserRelationType.Friends;
                        friend.Status = BasicData.UserRelationStatus.Established;
                        friend.CreatedTime = relation.CreatedTime;
                        reps.Add(friend);

                        // 删除好友申请的消息
                        // FIREND_REQ接收人_请求人
                        string identityText = string.Format("FIREND_REQ{0}_{1}", userId, targetUserId);
                        new MessageService().DeleteMessageClip2(dbContext, BasicData.MessageClipType.SystemNotice, identityText);

                        MessageRepository msgReps = new MessageRepository(dbContext);
                        MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);
                        // 发送消息给对方通知对方好友申请通过
                        string feedbackIdentity = string.Format("FRIENDREQUEST_ACCEPT{0}-{1}", targetUserId, userId);
                        Message message = new Message();
                        message.Id = Guid.NewGuid();
                        message.ReceiverId = targetUserId;
                        message.SenderId = userId;
                        message.Type = BasicData.MessageType.AcceptFriendsRequest;
                        message.Title = "好友申请通过";
                        message.Content = string.Format("{0}同意你的好友申请", user.NickName);
                        message.CreatedTime = DateTime.Now;

                        // 生成MessageSet
                        MessageClip messageSet = new MessageClip();
                        messageSet.Id = Guid.NewGuid();
                        messageSet.IdentityText = feedbackIdentity;
                        messageSet.Type = BasicData.MessageClipType.SystemNotice;
                        messageSet.MessageType = BasicData.MessageType.AcceptFriendsRequest;
                        messageSet.ReceiverId = targetUserId;
                        messageSet.MessageCount = 1;
                        messageSet.NewMessageCount = 1;
                        messageSet.CreatedTime = message.CreatedTime;
                        messageSet.LastestSenderId = message.SenderId;
                        messageSet.LastestContent = message.Content;
                        messageSet.LastestTitle = message.Title;
                        messageSet.LastestUpdatedTime = message.CreatedTime;

                        message.MessageClipId = messageSet.Id;

                        msgSetReps.Create(messageSet);
                        msgReps.Create(message);

                        if (dbContext.SaveChanges() > 0)
                        {
                            return new ServiceResult<UserRelation>(ErrorCode.NoError, relation);
                        }
                        return new ServiceResult<UserRelation>(ErrorCode.DB_Error);
                    }
                }
                else
                {
                    return new ServiceResult<UserRelation>(ErrorCode.AcceptFriendsRequest_NoRequest);
                }
            }
        }

        public ServiceResult<UserRelation> RejectRequest(int userId, int targetUserId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                AccountRepository aReps = new AccountRepository(dbContext);
                Account user = aReps.Get(userId);
                UserRelationRepository reps = new UserRelationRepository(dbContext);
                UserRelation relation = reps.Get(userId, targetUserId, BasicData.UserRelationType.Friends);

                if (relation != null)
                {
                    if (relation.Status == BasicData.UserRelationStatus.Building)
                    {
                        // 删除好友申请
                        reps.Delete(relation);

                        // 删除好友申请的消息
                        // FIREND_REQ接收人_请求人
                        string identityText = string.Format("FIREND_REQ{0}_{1}", userId, targetUserId);
                        new MessageService().DeleteMessageClip2(dbContext, BasicData.MessageClipType.SystemNotice, identityText);

                        MessageRepository msgReps = new MessageRepository(dbContext);
                        MessageClipRepository msgSetReps = new MessageClipRepository(dbContext);
                        // 发送消息给对方通知对方好友申请失败
                        string feedbackIdentity = string.Format("FRIENDREQUEST_REJECT{0}-{1}", targetUserId, userId);
                        Message message = new Message();
                        message.Id = Guid.NewGuid();
                        message.ReceiverId = targetUserId;
                        message.SenderId = userId;
                        message.Type = BasicData.MessageType.RejectFriendsRequest;
                        message.Title = "好友申请失败";
                        message.Content = string.Format("{0}拒绝了你的好友申请", user.NickName);
                        message.CreatedTime = DateTime.Now;

                        // 生成MessageSet
                        MessageClip messageSet = new MessageClip();
                        messageSet.Id = Guid.NewGuid();
                        messageSet.IdentityText = feedbackIdentity;
                        messageSet.Type = BasicData.MessageClipType.SystemNotice;
                        messageSet.MessageType = BasicData.MessageType.RejectFriendsRequest;
                        messageSet.ReceiverId = targetUserId;
                        messageSet.MessageCount = 1;
                        messageSet.NewMessageCount = 1;
                        messageSet.CreatedTime = message.CreatedTime;
                        messageSet.LastestSenderId = message.SenderId;
                        messageSet.LastestContent = message.Content;
                        messageSet.LastestTitle = message.Title;
                        messageSet.LastestUpdatedTime = message.CreatedTime;

                        message.MessageClipId = messageSet.Id;

                        msgSetReps.Create(messageSet);
                        msgReps.Create(message);

                        if (dbContext.SaveChanges() > 0)
                        {
                            return new ServiceResult<UserRelation>(ErrorCode.NoError, relation);
                        }
                        return new ServiceResult<UserRelation>(ErrorCode.DB_Error);
                    }
                }
                return new ServiceResult<UserRelation>(ErrorCode.RejectFriendsRequest_NoRequest);
            }
        }

        public ServiceResult<UserRelation> Delete(int userId, int targetUserId)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {
                UserRelationRepository reps = new UserRelationRepository(dbContext);

                UserRelation friend = reps.Get(userId, targetUserId, BasicData.UserRelationType.Friends, BasicData.UserRelationStatus.Established);
                UserRelation friend2 = reps.Get(targetUserId, userId, BasicData.UserRelationType.Friends, BasicData.UserRelationStatus.Established);

                if (friend != null && friend2 != null)
                {
                    reps.Delete(friend);
                    reps.Delete(friend2);

                    if (dbContext.SaveChanges() > 0)
                    {
                        return new ServiceResult<UserRelation>(ErrorCode.NoError, friend);
                    }
                    return new ServiceResult<UserRelation>(ErrorCode.DB_Error);
                }
                return new ServiceResult<UserRelation>(ErrorCode.NoError);
            }
        }
    }
}
